import React from 'react';
import './goodsLabel.less';
import { Layout, Breadcrumb, Icon, Tag, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import { Link, hashHistory } from 'react-router';

const FormItem = Form.Item;
const config = new Config()
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const { TextArea } = Input;
const token = sessionStorage.getItem('token')

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false, //菜单折叠状态
            mode: 'inline', //菜单显示模式，垂直 or 行内
            Openvisible: false, //增加，弹出框
            Closevisible: false, //关闭，弹出框
            producttaglist: [],//商品标签列表
            producttagcount: 0,//商品标签条数
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            tagname: '',//商品标签名
            tagstatus: undefined,//商品标签状态
            OperationTagID: '0',//操作标签ID
            OperationStatus: '',//操作状态
            OperationTagName: '',//操作标签名称
            AddTagStatus: true,//受控制的多选框
            tagid: "", //编辑的tag id 
        }
    }

    componentDidMount() {
        this.GetProductTagList();
    }
    //商品标签列表
    GetProductTagList() {
        $.ajax({
            url: `${config.JuseProduct}/tags/list`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                tagName: this.state.tagname,
                state: this.state.tagstatus,
            },
            success: res => {
                console.log('商品标签列表', res)
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.key = index + 1
                    })
                    this.setState({
                        producttaglist: res.data.rows,
                        producttagcount: res.data.count,
                    });
                }
            }
        });
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.GetProductTagList();
        });
    }
    //状态改变事件
    tagstatusChange(v) {
        this.setState({
            tagstatus: v
        });
    }
    //搜索
    searchBtn() {
        const form = this.props.form;
        this.setState({
            tagname: form.getFieldValue('txt_TagName') ? form.getFieldValue('txt_TagName') : '',
            pageindex: 1,
        }, () => {
            this.GetProductTagList();
        });
    }
    //重置
    resetBtn() {
        const form = this.props.form;
        form.setFieldsValue({ txt_TagName: "" });
        this.setState({
            pageindex: 1,
            tagstatus: undefined,
            tagname: undefined
        }, () => {
            this.GetProductTagList();
        });
    }

    //新增/编辑对话框
    OpenshowModal(record, e) {
        if (record) {
            this.props.form.setFieldsValue({
                'txt_tagnameAdd': record.tagName,
                'txt_tagdescribeAdd': record.describe,
                'ck_tagstatusAdd': record.state ? true : false
            })
            this.setState({
                tagid: record.tagId,
                Openvisible: true,
            });
        } else {
            this.props.form.resetFields();
            this.setState({
                tagid: "",
                Openvisible: true,
            });
        }
    }
    //确定新增/编辑
    OpenhandleOk() {
        const form = this.props.form;
        const { tagid } = this.state;
        form.validateFields((err, values) => {
            console.log(values)
            if (!err) {
                const data = {
                    tagName: values.txt_tagnameAdd,
                    describe: values.txt_tagdescribeAdd,
                    state: values.ck_tagstatusAdd ? 1 : 0,
                }
                let url;
                if (tagid) {
                    url = `${config.JuseProduct}/tags/update`;
                    data.tagId = tagid;
                } else {
                    url = `${config.JuseProduct}/tags/add`;
                }
                $.ajax({
                    url: url,
                    type: "post",
                    data: data,
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    success: res => {
                        console.log(res)
                        if (res.code === 200) {
                            this.setState({
                                Openvisible: false,
                            }, () => {
                                this.GetProductTagList();
                            });
                        }
                    }
                });
            } else {
                message.error('请填写必要的信息，再提交', 2);
            }
        })
    }
    //取消新增/编辑
    OpenhandleCancel() {
        this.setState({
            Openvisible: false,
        });
    }

    //关闭/启用标签对话框
    CloseshowModal(tagid, tagstatus, tagname) {
        this.setState({
            OperationTagID: tagid,
            OperationStatus: tagstatus,
            OperationTagName: tagname,
            Closevisible: true,
        });
    }
    //确定启用/关闭商品标签
    ClosehandleOk(tagid, tagstatus, tagname) {
        $.ajax({
            url: `${config.JuseProduct}/tags/operation`,
            type: "post",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                tagId: tagid,
                state: tagstatus ? 0 : 1,
            },
            async: true,
            success: res => {
                if (res.code === 200) {
                    this.setState({
                        Closevisible: false,
                    }, () => {
                        this.GetProductTagList();
                    });
                }
            }
        });
    }
    //取消确定启用/关闭商品标签
    ClosehandleCancel() {
        this.setState({
            Closevisible: false,
        });
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;

        const columns = [{
            title: '序号',
            dataIndex: 'key',
            width: 100
        }, {
            title: '标签名称',
            dataIndex: 'tagName',
            width: 300
        }, {
            title: '使用量',
            dataIndex: 'useCount',
            render: (text, record) => {
                if (text > 0) {
                    const path = {
                        pathname: '/allgoods',
                        state: { 'tagname': record.tagName },
                    }
                    return <Link to={path}>{text}</Link>
                } else {
                    return text;
                }
            },
            width: 100
        }, {
            title: '状态',
            dataIndex: 'state',
            render: text => text === 1 ? "启用" : "禁用",
            width: 100
        }, {
            title: '操作',
            dataIndex: '',
            render: (text, record) => <a onClick={this.CloseshowModal.bind(this, record.tagId, record.state, record.tagName)}>{record.state === 0 ? "启用" : "关闭"}</a>,
            width: 100
        }, {
            title: '操作',
            dataIndex: 'edit',
            render: (text, record) => <a onClick={this.OpenshowModal.bind(this, record)}>编辑</a>,
            width: 100
        }];
        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>商品标签管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_TagName')(
                                            <Input className='addetd-a-r' addonBefore="标签名" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="状 态" />
                                    <Select value={this.state.tagstatus} onChange={this.tagstatusChange.bind(this)} placeholder='请选择'>
                                        <Option value="1">已启用</Option>
                                        <Option value="0">已禁用</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <Button type="primary" className='member-button' icon="search" onClick={this.searchBtn.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.resetBtn.bind(this)}>重置</Button>
                        </div>
                        <div className='goods-label-table clearfix'>
                            <Table
                                columns={columns}
                                dataSource={this.state.producttaglist}
                                pagination={false}
                                bordered
                            />
                            <div className='goods-label-tabletr'>
                                <Button className='goods-label-table-app' onClick={this.OpenshowModal.bind(this)} icon="plus">新增</Button>
                            </div>
                            <Modal title="新增" wrapClassName="vertical-center-modal" visible={this.state.Openvisible}
                                onOk={this.OpenhandleOk.bind(this)} onCancel={this.OpenhandleCancel.bind(this)}
                                footer={false}
                                width={380}
                                maskClosable={false}
                            >
                                <div className='goods-abut-a goodstag-modalform'>
                                    <FormItem>
                                        {
                                            getFieldDecorator('txt_tagnameAdd', {
                                                rules: [{ required: true, max: 10, message: '请输入标签名，不超过10个字' }],
                                            })(
                                                <p><span className='goods-abut-a-span'>标签名称</span>
                                                    <i><Input value={getFieldValue('txt_tagnameAdd')} placeholder="请输入标签名" /><span className='styleTagName'>*</span></i>
                                                </p>
                                            )
                                        }
                                    </FormItem>
                                    <FormItem>
                                        {
                                            getFieldDecorator('txt_tagdescribeAdd', {
                                                rules: [{ required: true, max: 50, message: '请输入标签描述，不超过50个字' }],
                                            })(
                                                <p><span className='goods-abut-a-span'>标签描述</span>
                                                    <i>
                                                        <TextArea value={getFieldValue('txt_tagdescribeAdd')} placeholder="请输入标签名称" rows={4} style={{ resize: "none" }} />
                                                        <span className='styleTagName'>*</span>
                                                    </i>
                                                </p>
                                            )
                                        }
                                    </FormItem>
                                    <FormItem>
                                        {getFieldDecorator('ck_tagstatusAdd', {
                                            initialValue: true,
                                        })(
                                            <p><i className='goods-abut-a-span-i'>是否开启&nbsp;&nbsp;&nbsp;<Checkbox checked={getFieldValue('ck_tagstatusAdd')}></Checkbox></i></p>
                                        )}
                                    </FormItem>
                                    <div className='goods-abut-a-button'>
                                        <Button type="primary" className='buttom-aa' onClick={this.OpenhandleOk.bind(this)}>确定</Button>
                                        <Button className='buttom-ab' onClick={this.OpenhandleCancel.bind(this)}>取消</Button>
                                    </div>
                                </div>
                            </Modal>
                            <div className='showmodele'>
                                <Modal title={this.state.OperationStatus == "0" ? "启用" : "关闭"} wrapClassName="vertical-center-modal" visible={this.state.Closevisible}
                                    onOk={this.ClosehandleOk.bind(this, this.state.OperationTagID, this.state.OperationStatus, this.state.OperationTagName)} onCancel={this.ClosehandleCancel.bind(this)}
                                    width={342}
                                    footer={null}
                                >
                                    <p className='showp'>您确定{this.state.OperationStatus == "0" ? "启用" : "关闭"}<i>{this.state.OperationTagName}</i>标签</p>
                                    <p className='showp-a'><Button type="primary" onClick={this.ClosehandleOk.bind(this, this.state.OperationTagID, this.state.OperationStatus, this.state.OperationTagName)} className='member-button member-button-a'> 确 定</Button></p>
                                </Modal>
                            </div>
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                {
                                    this.state.producttagcount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.producttagcount}条记录
                                </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.producttagcount ? this.state.pagesize * this.state.pageindex : this.state.producttagcount}条记录，
                                    共{this.state.producttagcount}条记录
                                </p>
                                }
                                <Pagination current={this.state.pageindex} total={this.state.producttagcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        )
    }
}

const GoodsLabel = Form.create()(RegForm);
export default GoodsLabel;